32% completed
Here is a step-by-step system design for Amazon S3 (Simple Storage Service).
1. Problem Definition and Scope
We are designing a highly scalable, durable object storage service. Unlike a file system, this is a Key-Value store where the "Key" is a URL path and the "Value" is a file (object) that can range from a few bytes to terabytes.
-
Main User Groups: Developers (storing app assets, logs), Systems (backups, big data analytics), and End Users (viewing content).
-
Main Actions: Create buckets, upload files (PUT), download files (GET), delete files, and list files.
-
Scope: We will focus on the Standard storage tier (hot data).
-
Out of Scope: We will not cover cold archival storage (Glacier), static website hosting, object lifecycle policies, or cross-region replication details.
2. Clarify functional requirements
Must have:
-
Buckets: Users can create named containers. Names must be globally unique.
-
Put Object: Users can upload files. The system must support small files (kilobytes) and very large files (terabytes).
-
Get Object: Users can retrieve files via HTTP.
-
Delete Object: Users can remove files.
-
List Objects: Users can list keys in a bucket, supporting pagination and prefix filtering.
-
Immutability: Objects are immutable. To modify a file, you must overwrite it completely.
Nice to have:
-
Multipart Upload: Ability to upload a single large file in parallel chunks.
-
Presigned URLs: Ability to grant temporary access to a private object via a URL.
3. Clarify non-functional requirements
-
Durability: The most critical requirement. Target 11 nines (99.999999999%). We must not lose data.
-
Availability: High (99.9% - 99.99%). The service should always accept writes and reads.
-
Scale: Must support Exabytes of data and Trillions of objects.
-
Performance: Optimized for throughput (streaming large files) rather than ultra-low latency. Time-to-first-byte should be < 100ms.
-
Consistency: Strong consistency for new objects. Once a client receives 200 OK for a write, a subsequent read must return that new data.
-
Cost: Must be cost-effective using commodity hardware.
4. Back of the envelope estimates
Let's design for a large regional deployment.
-
Traffic:
- Writes: 100,000 QPS.
- Reads: 1,000,000 QPS (10:1 read-to-write ratio).
-
Storage:
- Average object size: 1 MB.
- Daily Ingress: 100,000 writes/sec x 1 MB ≈ 100GB/sec.
- Daily Storage: 100 GB/sec x 86,400 sec ≈ 8.6 PB/day.
- Yearly Storage: ≈ 3 Exabytes.
-
Bandwidth:
- Ingress: 100 GB/sec.
- Egress: 1,000,000 reads/sec x 1 MB = 1 TB/sec.
- Note: This confirms we need a massive, distributed architecture.
5. API design
We will use a RESTful API. BucketName acts as the namespace.
-
Upload Object
- PUT /:bucketName/:objectKey
- Headers: Content-Length, Content-Type, x-amz-acl.
- Body: Binary file stream.
- Response: 200 OK (ETag: MD5 hash).
- Errors: 403 Forbidden, 400 Bad Request.
-
Get Object
- GET /:bucketName/:objectKey
- Headers: Range: bytes=0-1000 (optional for partial fetch).
- Response: 200 OK (Body: binary data).
-
Delete Object
- DELETE /:bucketName/:objectKey
- Response: 204 No Content.
-
List Objects
- GET /:bucketName
- Params: prefix (filter), max-keys (limit), continuation-token (cursor).
- Response: JSON list of object metadata (Key, Size, LastModified).
6. High-level architecture
We separate the system into two main planes: the Metadata Plane (file info) and the Data Plane (actual content).
Client -> Load Balancer -> API Service -> Metadata Service + Blob Store
-
Load Balancer: Distributes HTTP requests to API servers. Terminates SSL.
-
API Service: Stateless front-end. Handles authentication (IAM), request validation, and orchestrates calls to the backend services.
-
Metadata Service: A distributed Key-Value store. It maps Bucket + Key to Location ID. It stores object attributes (size, owner, permissions).
-
Blob Store (Data Plane): A massive cluster of storage nodes (Data Nodes). It stores the actual immutable chunks of data.
-
Placement Service: A background coordinator that monitors Data Nodes and decides where new data should be written to ensure balance.
7. Data model
We need two different storage engines.
A. Metadata Storage (Key-Value Store)
We cannot use a standard SQL DB for trillions of objects. We need a sharded, high-performance KV store (e.g., Apache Cassandra, DynamoDB, or a sharded CockroachDB).
- Table: ObjectMetadata
- PartitionKey: Hash(BucketName). See Scaling section for hot buckets.
- SortKey: ObjectKey (e.g., /photos/cat.jpg). This allows listing by prefix.
- ObjectUUID: Unique internal ID.
- Size: BigInt.
- LocationList: JSON List of [VolumeID, Offset, Length].
B. Blob Storage (Aggregated Files)
Storing billions of small 10KB files as individual files on a Linux filesystem (ext4) causes inode exhaustion and poor performance.
-
Aggregation: We pack many small objects into large physical "Read-Only Data Files" (e.g., 1 GB size), similar to Facebook's "Haystack" design.
-
Addressing: The Metadata Service points to a VolumeID (which file), an Offset (byte start), and Length.
8. Core flows end to end
In a distributed object store, the system's reliability depends on the strict coordination between the Metadata Service (the index) and the Blob Store (the actual data).
We will detail the four most critical flows: Uploading, Downloading, Multipart Upload (for large files), and Deleting.
Flow 1: Uploading a File (PUT Object)
Scenario: A user uploads a 5MB image (cat.jpg).
Goal: Strong Consistency. We must ensure the file is safe on disk before telling the user "Success."
This is the most critical flow. We cannot simply save the file to the API server's disk; we must replicate it across the cluster to survive hardware failures.
-
Request & Validation: The Client sends a
PUT /bucket/cat.jpgrequest. The API Service authenticates the user (IAM) and validates the request headers (e.g., Content-Length). -
Placement Strategy (The "Where"): The API Service asks the Placement Service: "I need to write 5MB. Which data nodes have space?" The Placement Service returns a list of 3 Data Nodes (e.g., Node A, Node B, Node C) located in different racks or Availability Zones.
-
Data Streaming (The Pipeline): The API Service initiates a stream. It does not download the file to its own RAM (buffering huge files would crash the server). It pipes the bytes directly from the Client to the first Data Node (Node A).
-
Chain Replication:
- Node A writes the data to its memory buffer and immediately pipes the stream to Node B.
- Node B pipes it to Node C.
- Why? This utilizes the network bandwidth of all nodes in parallel (pipelining) rather than writing sequentially.
- The write is blocked until Node C (the tail) confirms the data is flushed to disk. Node C sends an acknowledgment (ACK) back to B, B sends to A, and A sends to the API Service.
- Metadata Commit (The "Pointer"):
- Critical Moment: The data is now safe on disk, but it is "orphan data"—invisible to users because the Metadata Service hasn't been updated yet.
- The API Service calls the Metadata Service to save the mapping:
"bucket/cat.jpg" -> { VolumeID: 123, Offset: 5000, Size: 5MB }
- Response:
The API Service returns
200 OKto the Client.
- Result: Because we update metadata only after the data is durable, we achieve Strong Consistency. A subsequent read will immediately find the new file.
Flow 2: Downloading a File (GET Object)
Scenario: A user requests GET /bucket/cat.jpg.
Goal: Low Latency and High Throughput.
Reads are optimized for speed. We decoupled "finding the data" from "reading the data."
- Metadata Lookup:
The API Service checks the Metadata Cache (e.g., Redis). If missing, it queries the DB: "Where is
cat.jpg?"
- Response: "It is in Volume 123 at Offset 5000, Length 5MB."
-
Node Selection: The API Service looks up which Data Nodes hold Volume 123. It selects the best node based on latency (network proximity) or load (least busy).
-
Direct Streaming: The API Service connects to the selected Data Node and requests the specific byte range.
- The Data Node seeks to
Offset 5000on its disk and streams the bytes back. - The API Service pipes the data immediately to the Client.
- Self-Healing: If the Data Node detects a checksum error (bit rot) during the read, the API Service transparently retries the request against a different replica node.
Flow 3: Multipart Upload (Handling Large Files)
Scenario: A user uploads a 50GB video file. Goal: Reliability. A single HTTP connection is too fragile for 50GB.
Uploading 50GB in a single stream is risky; a network blip at 99% would force a total restart. We solve this by breaking the file into independent chunks.
- Initialization:
The Client requests to start a multipart upload. The API Service generates a unique
UploadID. - Parallel Uploads:
The Client splits the file locally into 100 parts (e.g., 500MB each) and uploads them in parallel (
PUT /...?partNumber=1,?partNumber=2).
- The system treats each Part exactly like a "Small Object" from Flow 1: it is streamed to Data Nodes and replicated for durability.
- The Metadata Service tracks these temporary parts:
UploadID -> [Part1: LocA, Part2: LocB...].
- Completion (Virtual Assembly): The Client sends a "Complete Upload" request. The API Service tells the Metadata Service to "stitch" the parts.
- The Playlist Analogy: We do not physically merge the 500MB chunks into one contiguous file on disk (that would be slow). Instead, the Metadata entry acts as a Playlist: "This object consists of Part 1 at Volume X + Part 2 at Volume Y..." The file is now logically one object and immediately ready for download.
Flow 4: Deleting a File (DELETE Object)
Scenario: A user deletes cat.jpg.
Goal: Fast feedback vs. System efficiency.
Physically deleting data from a hard drive is an expensive random I/O operation (and impossible in the middle of a sequential file). We use Soft Deletes.
- Metadata Update:
The Client sends
DELETE /bucket/cat.jpg. The API Service updates the Metadata Service, marking the key asDELETED(or removing the row). The API Service returns204 No Content.
- User View: The file is gone. Any subsequent
GETreturns404 Not Found.
- Async Garbage Collection (The Cleanup): The actual binary bytes still exist on the Data Node's disk inside Volume 123.
A background Compactor Service scans volumes. When it finds a volume with significant "deleted" data (e.g., >40% waste), it:
- Copies the remaining live objects to a new volume (e.g., Volume 999).
- Updates the Metadata to point to the new location.
- Physically deletes the old Volume 123 entirely, reclaiming the disk space.
9. Caching and read performance
We cannot hit the disk for 1 million reads/sec.
- Metadata Caching:
- Use a distributed cache (Redis/Memcached) in front of the Metadata DB.
- Cache Bucket+Key -> Location.
- Use "Write-through" or short TTLs to keep it consistent.
- Content Caching:
- CDN (CloudFront): Customers should configure a CDN. This offloads read traffic to edge locations globally.
- Node-Level Cache: Data Nodes use OS page cache (RAM) to keep frequently accessed "hot" chunks in memory.
10. Storage, indexing, and media
Durability via Erasure Coding:
-
Replicating every 1TB file 3 times (3TB usage) is too expensive (200% overhead).
-
For warm/cold data, we use Erasure Coding (EC).
- Split data into k data chunks (e.g., 6) and m parity chunks (e.g., 3).
- Store these 9 chunks on 9 different drives/racks.
- We can lose any 3 drives and still reconstruct the file.
- Overhead is only 50% (much better than 200%).
Indexing:
-
The Metadata Store is the index.
-
Because we use BucketName as the Partition Key and ObjectKey as the Sort Key, we can efficiently perform Range Scans for the ListObjects API (e.g., WHERE partition=bucket AND sort_key LIKE 'photos/%').
11. Scaling strategies
Scaling Metadata:
-
Sharding: We shard the Metadata table by Hash(BucketName).
-
Hot Buckets: A single bucket with billions of objects (e.g., "logs") will overload one shard.
- Solution: Detect massive buckets and shard them further by Hash(BucketName + Prefix). This spreads the bucket across multiple nodes, but makes "Listing all objects in the bucket" slightly more complex (requires scatter-gather query).
Scaling Data:
-
Multipart Upload: For files > 100MB, the client splits the file into parts and uploads them in parallel to different API endpoints. The Metadata Service tracks these "parts" and virtually assembles them when the client sends a "Complete Multipart Upload" request.2
-
Throughput: By pipelining writes and allowing parallel range-reads, we saturate network links rather than waiting for disk seek times.
12. Reliability, failure handling, and backpressure
Failure Handling:
-
Bit Rot: Hardware disks silently flip bits. We store a Checksum (CRC/MD5) with every chunk. On read, the Data Node calculates the checksum. If it fails, it returns an error, and the API Service fetches from a replica.
-
Self-Healing: A background "Scrubber" process constantly scans disks. If a block is corrupted or a disk is dead, it reconstructs the missing data from parity chunks and writes it to a new healthy node.
-
Rack Awareness: We ensure replicas/EC chunks are placed on different racks and ideally different Availability Zones (AZs) to survive power outages or fires.
Backpressure:
- If a bucket exceeds its QPS limits (noisy neighbor), the API Service returns 503 Service Unavailable or 429 Too Many Requests.
- Clients are expected to implement Exponential Backoff (retry after 1s, 2s, 4s...).
13. Security, privacy and abuse
-
Authentication: All requests must be signed (e.g., HMAC-SHA256 signature). The API Service verifies this against the user's secret keys.
-
Presigned URLs: Allows a user to generate a URL with an embedded signature and expiration (e.g., 5 minutes) to let a third party upload/download directly without sharing credentials.3
-
Encryption:
- In Transit: TLS (HTTPS).
- At Rest: Server-Side Encryption (SSE). S3 encrypts the data key with a master key (KMS) before writing to disk.
14. Bottlenecks and next steps
- Bottleneck: Metadata Listing. Listing a bucket with 1 billion objects is slow in a key-value store, especially with hot-bucket sharding.
- Next Step: Implement a separate specialized search index (e.g., Elasticsearch) or a hierarchical directory index purely for ListObjects calls, decoupled from the core read/write path.
- Bottleneck: Bandwidth. 1 TB/sec egress is a massive network load.
- Next Step: Implement "Intelligent Tiering" to move cold data to cheaper, slower media (like Tape/Glacier) automatically to save cost and bandwidth capacity for hot data.
Summary
-
Architecture: Separated Metadata (KV Store) from Data (Blob Store).
-
Efficiency: Used Aggregation (packing small files into Volumes) to solve inode exhaustion.
-
Durability: Used Erasure Coding (6+3) to achieve 11 nines durability efficiently.4
-
Scale: Sharded metadata by hash and used parallel Multipart Uploads for throughput.
On this page
1. Problem Definition and Scope
2. Clarify functional requirements
3. Clarify non-functional requirements
4. Back of the envelope estimates
5. API design
6. High-level architecture
7. Data model
8. Core flows end to end
Flow 1: Uploading a File (PUT Object)
Flow 2: Downloading a File (GET Object)
Flow 3: Multipart Upload (Handling Large Files)
Flow 4: Deleting a File (DELETE Object)
9. Caching and read performance
10. Storage, indexing, and media
11. Scaling strategies
12. Reliability, failure handling, and backpressure
13. Security, privacy and abuse
14. Bottlenecks and next steps
Summary